export default {
    namespaced: true,
    state: {
        name: "产品product",
        products: []
    },
    actions: {
        //async 异步 await 等待异步Promise结果
        //async 函数内部,使用await 可以将异步的代码变成'同步'执行的顺序
        async FETCH_PRODUCT({ commit }) {
            let res = await fetch('/api/data/index.json?name=lilei').then(body => body.json())
            console.log(res)
            //提交给mutation进行修改
            commit('SET_PRODUCT', res.data)
        }
    },
    getters: {},
    mutations: {
        //获取产品数据
        SET_PRODUCT(state, payload) {
            state.products = payload
        },
        // 库存减少
        DECREASE_INVENTORY(state, payload) {
            //需要知道让那一条数据的库存减少
            // console.log(payload)
            // 将数据从state.products中查找出来,然后将inventory进行--
            let target = state.products.find(item => item.id === payload.id)

            if (target) {
                target.inventory--
            }
        },
        //库存增加
        INCREASE_INVENTORY(state, payload) {
            // 通过payload的id, 找到state.products中对应的数据, 让inventory + 1
            let target = state.products.find(item => item.id === payload.id)

            if (target) {
                target.inventory++
            }
        }
    }
}